package com.candy.control;

import com.candy.service.LoginService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
//        获取初始化参数
        String initParam=config.getInitParameter("init");
        System.out.println("获取初始化参数"+initParam);
//        获取ServletContext对象
        System.out.println("获取servletContext");
        ServletContext context=config.getServletContext();
        String contextParam=context.getInitParameter("contextParam");
        System.out.println("获取的contextParam："+contextParam);
    }

    //    处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("已接收前端传过来的请求...");
//        处理中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
//        接收客户端传递进来的数据
        String username=req.getParameter("username");
        String userpwd=req.getParameter("userpwd");
//        调用业务逻辑处理层，进行处理登录逻辑
        LoginService service=new LoginService();
        boolean ok=service.login(username,userpwd);
        if(ok){
//            若用户名密码匹配，则跳转到登陆成功页面
//            转发
            req.getRequestDispatcher("layout.html").forward(req,resp);
        }else {
//            若不匹配，返回登录页面
//           重定向
            resp.sendRedirect("login.jsp");
        }
    }
//处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
